
package com.yimixian.app.util;

import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.common.Constants;
import com.yimixian.app.common.StatConstants;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.model.WechatOrder;
import com.yimixian.app.order.ConfirmOrderActivity;
import com.yimixian.app.payment.AlipayPayResult;
import com.yimixian.app.payment.PaymentController;
import com.yimixian.app.rest.YmxDataService;
import com.yimixian.app.ui.ProgressDialogFragment;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

import android.app.Activity;
import android.text.TextUtils;
import android.webkit.WebView;

/**
 * Created by songzy on 2015/9/21.
 */
public class PayUtils {
    private static PayUtils mPayUtils;
    private Activity mActivity;
    public ProgressDialogFragment mProgressDialog;
    public WechatOrder mWechatOrder;
    public IWXAPI mWxApi;
    public boolean mStartedWechatPay = false;
    private String mCallBack = "";
    private WebView mWebView;
    private String mAlipayString;
    public String mPaymentId;

    private PayUtils() {

    }

    public static PayUtils getInstance() {
        if (mPayUtils == null) {
            mPayUtils = new PayUtils();
        }
        return mPayUtils;
    }

    public void startPay(String payMethod, String paymentId) {
        mWxApi = WXAPIFactory.createWXAPI(mActivity, Constants.WECHAT_APP_ID);
        mPaymentId = paymentId;
        String dialogText;
        switch (payMethod) {
            case (ConfirmOrderActivity.PAYMENT_METHOD_ALIPAY):
                dialogText = "打开支付宝...";
                break;
            case (ConfirmOrderActivity.PAYMENT_METHOD_WECHAT):
                dialogText = "打开微信支付...";
                break;
            case (ConfirmOrderActivity.PAYMENT_METHOD_BALANCE):
                dialogText = "支付中...";
                break;
            default:
                dialogText = "支付中...";
                break;
        }
        mProgressDialog = UiUtils.showProgressDialog(mActivity, dialogText);
        String payId = paymentId;
        if (TextUtils.isEmpty(payId)) {
            UiUtils.showToast(mActivity,"支付异常,订单号为空");
            return;
        }
        if (!TextUtils.isEmpty(payId)) {
            startPayment(payMethod, payId);
            return;
        }
    }

    public void startPayment(String mCurrentPayMethodName, String payId) {
        switch (mCurrentPayMethodName) {
            case (ConfirmOrderActivity.PAYMENT_METHOD_ALIPAY):
                fetchAlipayString(payId);
                MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                        StatConstants.CONFIRM_ORDER_ALIPAY_CLICK);
                break;
            case (ConfirmOrderActivity.PAYMENT_METHOD_WECHAT):
                MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                        StatConstants.CONFIRM_ORDER_WECHAT_CLICK);
                fetchWechatOrder(payId);
                break;
            case (ConfirmOrderActivity.PAYMENT_METHOD_BALANCE):
                MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                        StatConstants.CONFIRM_ORDER_BALANCE_CLICK);
                payWithBalance(payId);
                break;
        }
    }

    // ------------------------------------微信支付开始--------------------------------------

    public void fetchWechatOrder(String payId) {

        YmxDataService.getInstance().payWithWechat(payId)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    new Action1<WechatOrder>() {
                        @Override
                        public void call(WechatOrder wechatOrder) {
                            mWechatOrder = wechatOrder;
                            payWithWechat();
                        }
                    },
                    new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            mProgressDialog = UiUtils.dismiss(mProgressDialog);
                            UiUtils.toastError(
                                SystemFramework.getInstance().getGlobalContext(),
                                throwable);
                        }
                    });
    }

    public void payWithWechat() {
        mStartedWechatPay = true;
        PayReq request = new PayReq();
        request.appId = mWechatOrder.appid;
        request.partnerId = mWechatOrder.partnerid;
        request.prepayId = mWechatOrder.prepayid;
        request.packageValue = mWechatOrder.packageValue;
        request.nonceStr = mWechatOrder.noncestr;
        request.timeStamp = mWechatOrder.timestamp;
        request.sign = mWechatOrder.sign;
        mWxApi.registerApp(Constants.WECHAT_APP_ID);
        mWxApi.sendReq(request);
    }

    public void onWechatPayFinished() {
        mProgressDialog = UiUtils.dismiss(mProgressDialog);
        mStartedWechatPay = false;
        Integer resultCode = DataManager.getInstance().get(mWechatOrder.prepayid);
        if (resultCode != null && resultCode == BaseResp.ErrCode.ERR_OK) {
            onPaymentSucceeded(ConfirmOrderActivity.PAYMENT_METHOD_WECHAT);
        } else {
            payFaild();
            UiUtils.showToast(SystemFramework.getInstance().getGlobalContext(), "支付失败");
        }
        removeAll();
    }

    // ------------------------------------微信支付结束--------------------------------------

    // ------------------------------------ALiPay支付开始--------------------------------------

    private void fetchAlipayString(String payId) {

        YmxDataService.getInstance().payWithAlipay(payId)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    new Action1<String>() {
                        @Override
                        public void call(String alipayOrderString) {
                            mAlipayString = alipayOrderString;
                            payWithAlipay();
                        }
                    },
                    new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            mProgressDialog = UiUtils.dismiss(mProgressDialog);
                            UiUtils.toastError(
                                SystemFramework.getInstance().getGlobalContext(),
                                throwable);
                        }
                    });
    }

    private void payWithAlipay() {
        PaymentController.getInstance().payWithAlipay(mAlipayString, mActivity)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    new Action1<AlipayPayResult>() {
                        @Override
                        public void call(AlipayPayResult result) {
                            mProgressDialog = UiUtils.dismiss(mProgressDialog);

                            if (TextUtils.equals(result.getResultStatus(), "9000")) {
                                onPaymentSucceeded(ConfirmOrderActivity.PAYMENT_METHOD_ALIPAY);
                            } else {
                                UiUtils.showToast(mActivity, result.getMemo());
                            }
                        }
                    },
                    new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            mProgressDialog = UiUtils.dismiss(mProgressDialog);
                            UiUtils.toastError(mActivity, throwable, "支付异常");
                            payFaild();
                        }
                    });
    }

    // ------------------------------------ALiPay支付结束--------------------------------------

    // ------------------------------------余额支付开始--------------------------------------
    private void payWithBalance(String payId) {

        YmxDataService.getInstance().payWithBalance(payId)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    new Action1<Boolean>() {
                        @Override
                        public void call(Boolean result) {
                            onPaymentSucceeded(ConfirmOrderActivity.PAYMENT_METHOD_BALANCE);
                        }
                    },
                    new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            mProgressDialog = UiUtils.dismiss(mProgressDialog);
                            UiUtils.toastError(
                                SystemFramework.getInstance().getGlobalContext(),
                                throwable);
                        }
                    });
    }

    // ------------------------------------余额支付结束--------------------------------------

    public void onPaymentSucceeded(String paymentMethod) {
        paySuccess();
        UiUtils.showToast(mActivity, "支付成功");
        mProgressDialog = UiUtils.dismiss(mProgressDialog);
        // if
        // (!paymentMethod.equals(ConfirmOrderActivity.PAYMENT_METHOD_BALANCE))
        // {
        // notifyPaySuc(mPaymentId, paymentMethod);
        // }
    }

    public void notifyPaySuc(String mPaymentId, String paymentmethod) {
        YmxDataService.getInstance().notifyPaySuc(mPaymentId, paymentmethod)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                    new Action1<String>() {
                        @Override
                        public void call(String info) {
                        }
                    },
                    new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {

                        }
                    });
    }

    public void paySuccess() {
        if (mWebView != null) {
            mWebView.loadUrl("javascript:" + mCallBack + "(1)");
        }
    }

    public void payFaild() {
        if (mWebView != null) {
            mWebView.loadUrl("javascript:" + mCallBack + "(0)");
        }
    }

    // ------------------------------------清除、设置绑定的view--------------------------------------

    /**
     * 移除所有绑定进来的view
     */
    private void removeAll() {
        mPaymentId = "";
        cancelCallBack();
        cancelWebView();
        cancelActivity();
    }

    public void setActivity(Activity activity) {
        this.mActivity = activity;
    }

    public void cancelActivity() {
        this.mActivity = null;
    }

    public void setCallBack(String callBack) {
        this.mCallBack = callBack;
    }

    public void cancelCallBack() {
        this.mCallBack = "";
    }

    public void setWebView(WebView webView) {
        this.mWebView = webView;
    }

    public void cancelWebView() {
        this.mWebView = null;
    }
}
